package com.qiaofang.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiaofang.common.config.SystemConfig;
import com.qiaofang.common.constant.CommonResponseCode;
import com.qiaofang.common.constant.DelFlagEnum;
import com.qiaofang.common.response.CommonResponse;
import com.qiaofang.common.utils.HttpUtil;
import com.qiaofang.common.utils.ParseUtils;
import com.qiaofang.dto.BaseResponseDto;
import com.qiaofang.entity.PremisesRelationExternal;
import com.qiaofang.entity.*;
import com.qiaofang.entity.enums.*;
import com.qiaofang.mapper.*;
import com.qiaofang.repository.OtherCompanyRepository;
import com.qiaofang.repository.PremisesDynamicExternalRepository;
import com.qiaofang.service.FHEstateService;
import com.qiaofang.service.PremisesRecommenderService;
import com.qiaofang.v10dto.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.net.URLDecoder;
import java.util.*;

@Service
@Slf4j
public class FHEstateServiceImpl implements FHEstateService {

    @Autowired
    private BaseCodeValueMapper baseCodeValueMapper;
    @Autowired
    private PremisesImageMapper premisesImageMapper;
    @Autowired
    private ApartmentLayoutDiagramMapper apartmentLayoutDiagramMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private PremisesRelationExternalMapper premisesRelationExternalMapper;
    @Autowired
    private PremisesRecommenderService premisesRecommenderService;
    @Autowired
    private PremisesDynamicExternalRepository dynamicExternalRepository;
    @Autowired
    private OtherCompanyRepository otherCompanyRepository;

    @Override
    public CommonResponse pushPremisesToV10(List<Premises> premisesList, List<OtherCompany> otherCompanyList) {
        CommonResponse response = new CommonResponse();
        StringBuffer sb = new StringBuffer();
        for(OtherCompany otherCompany: otherCompanyList){
            sb.append("公司:" + otherCompany.getCompanyName() + ",");
            Long successCount = 0L;
            Long failureCount = 0L;
            for(Premises premises: premisesList){
                Long premisesId = premises.getId();
                Long agentCompanyId = otherCompany.getChannelCompanyId();
                String companyUuid = otherCompany.getCompanyUuid();
                try{
                    log.info("FHEstateService --> pushMsgToV10 --> 开始推送 --> 分销公司Id: {}, V10公司: {}, 楼盘: {}", agentCompanyId, companyUuid, premisesId);
                    //整理参数
                    SaveFirsthandEstateReqDto reqDto = setSaveFirstHandEstateDto(premises);
                    reqDto.setCompanyUuid(otherCompany.getCompanyUuid());
                    reqDto.setAppId(otherCompany.getAppid());
                    reqDto.setAppkey(otherCompany.getAppkey());

                    //查询楼盘关联表中是否有关联数据
                    Example example = new Example(PremisesRelationExternal.class);
                    example.createCriteria().andEqualTo("isDeleted", DelFlagEnum.UNDEL.getNo())
                            .andEqualTo("sysId", ExternalSysEnum.V10.getCode())
                            .andEqualTo("externalCompanyId", otherCompany.getCompanyUuid())
                            .andEqualTo("premisesId", premises.getId());
                    List<PremisesRelationExternal> premisesRelationExternalList = premisesRelationExternalMapper.selectByExample(example);
                    if (premisesRelationExternalList != null && premisesRelationExternalList.size() > 0) {
                        reqDto.setEstateUuid(premisesRelationExternalList.get(0).getExternalId());
                    }else{
                        reqDto.setEstateUuid(null);
                    }
                    //请求接口
                    String result = HttpUtil.doPostV10(
                            SystemConfig.v10Url + SystemConfig.saveFirsthandEstate,
                            JSONObject.toJSONString(reqDto),
                            otherCompany.getAppid(),
                            otherCompany.getAppkey(),
                            otherCompany.getCompanyUuid());
                    System.out.println("--------------->result" + result);
                    BaseResponseDto<String> brDto = JSONObject.parseObject(result, BaseResponseDto.class);
                    //返回成功将其更新到 关联关系中
                    if (V10ApiResponseCodeEnum.SUCCESS.getNo().equals(brDto.getResponseCode())
                            && (premisesRelationExternalList == null || premisesRelationExternalList.size() == 0)) {
                        PremisesRelationExternal pre = new PremisesRelationExternal();
                        pre.setAgentCompanyId(otherCompany.getChannelCompanyId());
                        pre.setExternalCompanyId(otherCompany.getCompanyUuid());
                        pre.setPremisesId(premises.getId());
                        pre.setExternalId(brDto.getData());
                        pre.setSysId(ExternalSysEnum.V10.getCode());
                        pre.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                        pre.setCreateTime(Calendar.getInstance().getTime());
                        pre.setUpdateTime(Calendar.getInstance().getTime());
                        premisesRelationExternalMapper.insertSelective(pre);
                    }
                    successCount++;
                    log.info("FHEstateService --> pushMsgToV10 --> 开始推送 --> 分销公司Id: {}, V10公司: {}, 楼盘: {}, 推送结果: {}", agentCompanyId, companyUuid, premisesId, JSONObject.toJSONString(brDto));
                }catch (Exception ex){
                    failureCount++;
                    log.error("FHEstateService --> pushMsgToV10 --> 开始推送 --> 分销公司Id: {}, V10公司: {}, 楼盘: {}, 异常: {}", agentCompanyId, companyUuid, premisesId, ex);
                }
            }
            sb.append("成功:" + successCount + "条,");
            sb.append("失败:" + failureCount + "条\n");
        }
        log.info("FHEstateService --> pushMsgToV10 --> 推送结果: {}", sb.toString());
        response.setResponseMessage(sb.toString());
        return response;
    }

    @Override
    public CommonResponse deletePremisesToV10(Premises premises, List<PremisesRelationExternal> premisesExternalList) {
        CommonResponse response = new CommonResponse();
        List<String> estateUuid = new ArrayList<String>();
        StringBuffer sb = new StringBuffer();
        String result = null;
        for(PremisesRelationExternal premisesRelationExternal: premisesExternalList) {
            try {
                OtherCompany otherCompany = otherCompanyRepository
                        .getOtherCompanyByUuid(premisesRelationExternal.getExternalCompanyId(),premisesRelationExternal.getAgentCompanyId());
                //查询楼盘关联表中是否有关联数据
                Example example = new Example(PremisesRelationExternal.class);
                example.createCriteria().andEqualTo("isDeleted", DelFlagEnum.UNDEL.getNo())
                        .andEqualTo("sysId", ExternalSysEnum.V10.getCode())
                        .andEqualTo("externalCompanyId", otherCompany.getCompanyUuid())
                        .andEqualTo("premisesId", premises.getId());
                List<PremisesRelationExternal> premisesRelationExternalList = premisesRelationExternalMapper.selectByExample(example);
                if (premisesRelationExternalList != null && premisesRelationExternalList.size() > 0) {
                    estateUuid.add(premisesRelationExternalList.get(0).getExternalId());
                } else {
                    response.setResponseMessage("v10中无该楼盘");
                    return response;
                }

                DeleteFirsthandEstateReqDto reqDto = new DeleteFirsthandEstateReqDto();
                reqDto.setEstateUuids(estateUuid);
                //请求接口
                result = HttpUtil.doPostV10(
                        SystemConfig.v10Url + SystemConfig.deleteFirsthandEstate,
                        JSONObject.toJSONString(reqDto),
                        otherCompany.getAppid(),
                        otherCompany.getAppkey(),
                        otherCompany.getCompanyUuid());
                BaseResponseDto<String> brDto = JSONObject.parseObject(result, BaseResponseDto.class);
                if (V10ApiResponseCodeEnum.SUCCESS.getNo().equals(brDto.getResponseCode())) {
                    sb.append("楼盘同步删除成功");
                } else {
                    sb.append("楼盘同步删除失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.info("FHEstateService --> deleteToV10 --> 删除结果: {}", sb.toString());
        response.setResponseMessage(sb.toString());
        return response;
    }


    @Override
    public CommonResponse pushDynamicToV10(PremisesDynamic premisesDynamic, List<PremisesDynamicExternal> externalList, List<PremisesRelationExternal> premisesExternalList) {
        CommonResponse response = new CommonResponse();
        StringBuffer sb = new StringBuffer();
        Long successCount = 0L;
        Long failureCount = 0L;
        for(PremisesRelationExternal premisesRelationExternal: premisesExternalList){
            boolean flag = true;
            for (PremisesDynamicExternal external : externalList){
                if (external.getExternalCompanyId().equals(premisesRelationExternal.getExternalCompanyId())){
                    flag = false;
                    OtherCompany otherCompany = otherCompanyRepository
                            .getOtherCompanyByUuid(external.getExternalCompanyId(),premisesRelationExternal.getAgentCompanyId());
                    try {
                        /** 将请求数据存入reqDto */
                        SaveFirsthandEstateDynamicRequestDto reqDto = new SaveFirsthandEstateDynamicRequestDto();
                        reqDto.setChannelDynamicId(external.getDynamicId());
                        reqDto.setDynamicUuid(external.getDynamicUuid());
                        reqDto.setEstateUuid(external.getPremisesUuid());
                        reqDto.setTitle(premisesDynamic.getTitle());
                        reqDto.setIssueMode("1");
                        reqDto.setShowStatus(Integer.parseInt(String.valueOf(premisesDynamic.getCanSee())));
                        /** 将楼盘动态内容与简介解码 */
                        if (null != premisesDynamic.getRemark()){
                            reqDto.setRemark(URLDecoder.decode(premisesDynamic.getRemark(), "utf-8"));
                        }
                        if (null != premisesDynamic.getContent()) {
                            reqDto.setContent(URLDecoder.decode(premisesDynamic.getContent(), "utf-8"));
                        }

                        //请求接口
                        String result = HttpUtil.doPostV10(
                                SystemConfig.v10Url + SystemConfig.saveFirsthandEstateDynamic,
                                JSONObject.toJSONString(reqDto),
                                otherCompany.getAppid(),
                                otherCompany.getAppkey(),
                                otherCompany.getCompanyUuid());
                        BaseResponseDto<String> brDto = JSONObject.parseObject(result, BaseResponseDto.class);
                        //返回成功将其更新到 关联关系中
                        if (V10ApiResponseCodeEnum.SUCCESS.getNo().equals(brDto.getResponseCode())) {
                            external.setDynamicUuid(brDto.getData());
                            external.setUpdateTime(Calendar.getInstance().getTime());
                            dynamicExternalRepository.save(external);
                        }
                        successCount++;
                    } catch (Exception e) {
                        failureCount++;
                    }
                }
            }
            if (flag) {
                OtherCompany otherCompany = otherCompanyRepository
                        .getOtherCompanyByUuid(premisesRelationExternal.getExternalCompanyId(),premisesRelationExternal.getAgentCompanyId());
                PremisesDynamicExternal external = new PremisesDynamicExternal();
                try {
                    /** 将请求数据存入reqDto */
                    SaveFirsthandEstateDynamicRequestDto reqDto = new SaveFirsthandEstateDynamicRequestDto();
                    reqDto.setChannelDynamicId(premisesDynamic.getId());
                    reqDto.setEstateUuid(premisesRelationExternal.getExternalId());
                    reqDto.setTitle(premisesDynamic.getTitle());
                    reqDto.setIssueMode("1");
                    reqDto.setShowStatus(Integer.parseInt(String.valueOf(premisesDynamic.getCanSee())));
                    /** 将楼盘动态内容与简介解码 */
                    if (null != premisesDynamic.getRemark()){
                        reqDto.setRemark(URLDecoder.decode(premisesDynamic.getRemark(), "utf-8"));
                    }
                    if (null != premisesDynamic.getContent()) {
                        reqDto.setContent(URLDecoder.decode(premisesDynamic.getContent(), "utf-8"));
                    }

                    //请求接口
                    String result = HttpUtil.doPostV10(
                            SystemConfig.v10Url + SystemConfig.saveFirsthandEstateDynamic,
                            JSONObject.toJSONString(reqDto),
                            otherCompany.getAppid(),
                            otherCompany.getAppkey(),
                            otherCompany.getCompanyUuid());
                    BaseResponseDto<String> brDto = JSONObject.parseObject(result, BaseResponseDto.class);
                    //返回成功将其更新到 关联关系中
                    if (V10ApiResponseCodeEnum.SUCCESS.getNo().equals(brDto.getResponseCode())) {
                        external.setDynamicUuid(brDto.getData());
                        external.setDynamicId(premisesDynamic.getId());
                        external.setExternalCompanyId(premisesRelationExternal.getExternalCompanyId());
                        external.setPremisesId(premisesRelationExternal.getPremisesId());
                        external.setPremisesUuid(premisesRelationExternal.getExternalId());
                        external.setSysId("1");
                        external.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                        external.setCreateTime(Calendar.getInstance().getTime());
                        dynamicExternalRepository.save(external);
                    }
                    successCount++;
                } catch (Exception e) {
                    failureCount++;
                }
            }
        }
        sb.append("成功:" + successCount + "条,");
        sb.append("失败:" + failureCount + "条\n");
        log.info("FHEstateService --> pushMsgToV10 --> 推送结果: {}", sb.toString());
        response.setResponseMessage(sb.toString());
        if (successCount >= 1){
            response.setResponseCode(CommonResponseCode.RC_SUCCESS.getResponseCode());
        }else{
            response.setResponseCode("-1");
        }
        return response;
    }


    @Override
    public CommonResponse deleteReportToV10(CustomerPremises report, OtherCompany otherCompany, ReportExternal reportExternal) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CommonResponse response = new CommonResponse();
        StringBuffer sb = new StringBuffer();

        UpdateFirsthandIntentionAuditStatusReqDto reqDto = new UpdateFirsthandIntentionAuditStatusReqDto();
        reqDto.setIntentionUuid(reportExternal.getReportUuid());
        /** 1 为无效报备  */
        reqDto.setAuditStatus("1");
        if (null!=report.getCreateTime()){
            reqDto.setReportPeriodTime(sdf.format(report.getCreateTime()));
        }
        reqDto.setRemark("运营后台删除报备");
        if (null!=report.getVisitBaohuTime()) {
            reqDto.setVisitTime(sdf.format(report.getVisitTime()));
        }
        /**
         * 原有的 报备审核状态:1,2,3,4(无效,待审,未到访,已到访)
         */
        if("-1".equals(report.getCustomerStatus())){
            reqDto.setOldAuditStatus("1");
        }else if ("0".equals(report.getCustomerStatus())){
            reqDto.setOldAuditStatus("2");
        }else if ("10".equals(report.getCustomerStatus())){
            reqDto.setOldAuditStatus("3");
        }else if ("6".equals(report.getCustomerStatus())){
            reqDto.setOldAuditStatus("4");
        }

        String result = null;
        //请求接口
        try {
            result = HttpUtil.doPostV10(
                    SystemConfig.v10Url + SystemConfig.updateFirsthandIntentionAuditStatus,
                    JSONObject.toJSONString(reqDto),
                    otherCompany.getAppid(),
                    otherCompany.getAppkey(),
                    otherCompany.getCompanyUuid());
            BaseResponseDto<String> brDto = JSONObject.parseObject(result, BaseResponseDto.class);
            if (V10ApiResponseCodeEnum.SUCCESS.getNo().equals(brDto.getResponseCode())) {
                sb.append("同步v10转为无效报备-成功");
            } else {
                sb.append("同步v10转为无效报备-失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("FHEstateService --> deleteToV10 --> 结果: {}", sb.toString());
        return response;
    }
    
    /**
     * 设置楼盘请求参数
     * @param dto
     * @return
     */
    private SaveFirsthandEstateReqDto setSaveFirstHandEstateDto(Premises dto){
        SaveFirsthandEstateReqDto returnDto = new SaveFirsthandEstateReqDto();
        // 查询楼盘推荐人
        List<SyncIntentionRecommenderReqDto> premisesRecommenderDtoList = premisesRecommenderService.selectListForIntentionRecommender(dto.getId());
        if(CollectionUtils.isNotEmpty(premisesRecommenderDtoList)){
            //楼盘推荐人推送
            returnDto.setRecommenders(premisesRecommenderDtoList);
        }else{
            returnDto.setRecommenders(null);
        }
        // 1.楼盘基础信息
        //楼盘uuid
        returnDto.setEstateUuid(dto.getEstateUuid());
        //楼盘名称
        returnDto.setEstateName(dto.getName());
        //楼盘地址
        returnDto.setAddress(dto.getPremisesAddress());
        //省、市、区
        if(Objects.nonNull(dto.getProvinceId())){
            returnDto.setProvince(areaMapper.selectByPrimaryKey(dto.getProvinceId()).getName());
        }
        if(Objects.nonNull(dto.getCityId())){
            returnDto.setCity(areaMapper.selectByPrimaryKey(dto.getCityId()).getName());
        }
        if(Objects.nonNull(dto.getAreaId())){
            returnDto.setArea(areaMapper.selectByPrimaryKey(dto.getAreaId()).getName());
        }

        //楼盘均价
        returnDto.setAveragePrice(ParseUtils.toFloat(dto.getAveragePrice()== null?null:dto.getAveragePrice().split("\\,")));
        //建筑类型
        if (StringUtils.isNotBlank(dto.getBuildingType())) {
            String ids = dto.getBuildingType();
            if (ids.indexOf(",") != -1) {
                String[] list = dto.getBuildingType().split(",");
                StringBuffer sb = new StringBuffer();
                for (String id : list) {
                    String name = AbroadBuildingTypeEnum.getByNo(id).getDes();
                    sb.append(name + ",");
                }
                if (sb.length() > 0) {
                    returnDto.setBuildingType(sb.toString().substring(0, sb.toString().length() - 1));
                }
            } else {
                returnDto.setBuildingType(AbroadBuildingTypeEnum.getByNo(ids).getDes());
            }
        }

        //现金奖
        returnDto.setCashPrize(ParseUtils.toFloat(dto.getDealAward()));
        //渠道楼盘id
        returnDto.setChannelPremises(dto.getId());
        //交房日期(无对应数据)

        //佣金模式 （1:比例，2：金额）
        if(StringUtils.isNotBlank(dto.getCommission())) {
            List<CommissionType> commissions = new ArrayList<>();
            JSONArray jsonArray = JSONObject.parseArray(dto.getCommission());
            if(jsonArray.size() > 0 ) {
                for(int ii=0; ii<jsonArray.size(); ii++) {
                    CommissionType commissionType = new CommissionType();
                    JSONObject jsonObject = jsonArray.getJSONObject(ii);
                    commissionType.setName(jsonObject.getString("name"));
                    if("元".equals(jsonObject.getString("type"))) {
                        commissionType.setType("2");
                    }else if("%".equals(jsonObject.getString("type"))) {
                        commissionType.setType("1");
                    }else{
                        commissionType.setType("3");
                    }
                    commissionType.setMoney(jsonObject.getString("typeValue"));
                    commissions.add(commissionType);
                }
            }
            returnDto.setCommissions(commissions);
        }

        //结佣方式
        if(dto.getCommissionWay() != null){
            returnDto.setCommissionWay( CommissionWayEnum.getDescByNo(dto.getCommissionWay()));
        }
        //公司uuid
//        returnDto.setCompanyUuid(commpanyUuid);
        //带看确认方式（不需要）
        returnDto.setContractStartDate(dto.getCooperationBeginTime());
        returnDto.setContractEndDate(dto.getCooperationEndTime());
        //合作规则
        returnDto.setCooRule(dto.getCooperationRule());
        returnDto.setDevelopers(dto.getBuildingCompany());
        //商圈 不需要
        //地下车位
        returnDto.setDownCarPort(ParseUtils.toInteger(dto.getDownCarPort()));
        //参考首付 不需要
        //项目人员1/2/3 不需要
        //项目描述
        returnDto.setEstateDesc(dto.getIntroduction());
        //楼盘名称
        returnDto.setEstateName(dto.getName());
        //项目特色
        returnDto.setFeatureType(getFeatureType(dto.getCodeName()));
        //绿化率
        returnDto.setGreeningRate(ParseUtils.toFloat(dto.getGreeningRate()));
        //是否主推 （0普通 1主推 默认0）
        returnDto.setHotStatus("0");
        //规划户数
        returnDto.setHouseHolds(ParseUtils.toInteger(dto.getHouseHolds()));
        //报备保护天数类型 以前为分钟
        returnDto.setIntentionIntervalType(StringUtils.isBlank(dto.getVisitProtectType()) ? "3" : dto.getVisitProtectType());
        //报备保护时间
        if(dto.getSaveDaysType() == null || TimeUnitTypeEnum.NONE.getNo().equals(dto.getSaveDaysType().toString())){
            returnDto.setIntentionInterval(ParseUtils.toInteger(dto.getVisitProtect()));
        }else{
            returnDto.setIntentionInterval(0);
        }
        // 渠道状态 默认在 审核通过之后才推楼盘信息 所以上下架状态都为0:上架
        if(SaleStatusEnum.type_3.getNo().equals(dto.getSaleStatus()) ){
            returnDto.setChannelIssuedStatus(ShelvesStatusEnum.type0.getNo());
        }else{
            returnDto.setChannelIssuedStatus(ShelvesStatusEnum.type1.getNo());
        }

        // 物业公司
        returnDto.setManageCompany(dto.getPropertyCompany());
        //楼盘最高、最低价 不需要
        //报备号码 1,2,3(全号、前三后四、前四后三)
        returnDto.setMobileRule("1");
        //参考月供 不需要
        //开盘日期
        returnDto.setOpenDate(dto.getOpeningTime());
        //其他佣金模式说明，其他结佣说明，其他确认方式描述 不需要
        returnDto.setPlotRatio(ParseUtils.toFloat(dto.getPlotRatio()));
        //委托方负责人 （现改为对接人电话）
        returnDto.setClientPrincipal(dto.getManager());
        // 手机号 项目经理联系方式 (现改为对接人)
        returnDto.setPrincipalMobile(dto.getMobile());
        // 物业费用
        returnDto.setPropertyFee(ParseUtils.toFloat(dto.getPropertyCharges()));
        // 产权年限
        if(StringUtils.isNotBlank(dto.getRightYears())){
            returnDto.setPropertyRight(dto.getRightYears() + "年");
        }
        // 物业类型 渠道仅为单选
        if (StringUtils.isNotEmpty(dto.getEstateType())) {
            String[] estateTypes = dto.getEstateType().split(",");
            StringBuilder sb = new StringBuilder();
            for(String et : estateTypes){
                sb.append(EstateTypeEnum.getByNo(et).getDes() + ",");
            }
            if(sb.length() > 0){
                sb.deleteCharAt(sb.length() - 1);
            }
            returnDto.setPropertyType(sb.toString());
        }
        // 备注
        returnDto.setRemark(dto.getRemark());
        // 销售进度
        returnDto.setSaleStatus(switchPremisesStatus(dto.getSaleStatus()) );
        // 最短报备时间
        returnDto.setShortestInterval(ParseUtils.toInteger(dto.getSpecialTime()));
        // 周边配套 交通状况 不需要
        //地上车位
        returnDto.setUpCarPort(ParseUtils.toInteger(dto.getUpCarPort()));
        // 到场保护时间：天
        if(dto.getSaveDaysType() == null || TimeUnitTypeEnum.NONE.getNo().equals(dto.getSaveDaysType().toString())){
            returnDto.setVisitInterval(ParseUtils.toInteger(dto.getSaveDays()));
        }else{
            returnDto.setVisitInterval(0);
        }
        // 楼盘带看奖
        returnDto.setVisitPrize(ParseUtils.toFloat(dto.getReward()));
        // 楼盘类型 1 渠道王  2 非渠道王
        returnDto.setEstateType("1");
        // 楼盘创建日期
        returnDto.setChannelCreateDate(dto.getCreateTime());
        // 楼盘更新日期
        returnDto.setChannelUpdateDate(dto.getUpdateTime());
        // 楼盘发布状态更改日期
        returnDto.setIssueStatusChangeDate(new Date());
        //交房日期
        returnDto.setCheckOutDate(dto.getCheckInTime());
        // 楼盘图片,户型图，户型
        Map<String,List> map = setPreimsesImage(dto.getId(),dto.getUrl());
        returnDto.setImages(map.get("PremisesImage"));
        returnDto.setHouseTypes(map.get("HouseType"));
        // 是否有推荐人

        returnDto.setHasRecommender(StringUtils.defaultIfBlank(dto.getHasRecommender(), "0"));
        //商圈
        returnDto.setPanoramicView(dto.getPanoramicView());

        return returnDto;
    }
    /**
     * 设置图片，户型
     * @param premiesiseId
     * @param coverImageUrl
     * @return
     */
    private Map<String,List> setPreimsesImage(Long premiesiseId, String coverImageUrl){
        Map<String,List> map = new HashMap<>();
        List<PremisesImageV10Dto> list = new ArrayList<>();
        List<HouseType> houseTypes = new ArrayList<>();
        // 封面
        PremisesImageV10Dto coverImage = new PremisesImageV10Dto();
        coverImage.setChannelImageId(premiesiseId);
        coverImage.setBackUpFlag(false);
        coverImage.setImageType("1");
        coverImage.setImageDesc("封面图");
        coverImage.setImageUrl(coverImageUrl);
        list.add(coverImage);
        //1 查询楼盘相册
        Example example = new Example(PremisesImage.class);
        example.createCriteria().andEqualTo("premisesId", premiesiseId)
                .andEqualTo("isDeleted", DelFlagEnum.UNDEL.getNo());
        List<PremisesImage> imageList = premisesImageMapper.selectByExample(example);
        for(PremisesImage pi : imageList){
            PremisesImageV10Dto imageV10Dto = new PremisesImageV10Dto();
            imageV10Dto.setBackUpFlag(false);
            imageV10Dto.setImageType(pi.getImageType());
            imageV10Dto.setImageDesc(pi.getImageDesc());
            imageV10Dto.setImageUrl(pi.getImageUrl());
            imageV10Dto.setChannelImageId(pi.getId());

            list.add(imageV10Dto);
        }
        // 2 户型图
        example = new Example(ApartmentLayoutDiagram.class);
        example.createCriteria().andEqualTo("delFlag", DelFlagEnum.UNDEL.getNo())
                .andEqualTo("premisesId", premiesiseId);
        List<ApartmentLayoutDiagram> aldList = apartmentLayoutDiagramMapper.selectByExample(example);
        for(ApartmentLayoutDiagram ald : aldList){
            // 图片 户型图 图片不在传到图片列表 直接放到对应户型
            //设置户型
            HouseType ht = new HouseType();
            ht.setBuildingArea(ParseUtils.toFloat(ald.getArea().split("\\,")));
            ht.setDecorate(ald.getDecoration());
            ht.setFamilyStructure(ald.getHouseStruct());
            ht.setHouseTypeName(ald.getHuxingName());
            ht.setChannelHouseTypeId(ald.getId());
            ht.setOrientation(ald.getOrientations());
            ht.setSellingPrice(ParseUtils.toFloat(ald.getAveragePrice()== null?null:ald.getAveragePrice().toString().split("\\,")));
            ht.setRemark(ald.getRemark());
            ht.setImageName(ald.getHuxingName());
            String url = ald.getUrl();
            if(StringUtils.isNotBlank(url)){
                String[] urlArr = url.split(";");
                if(urlArr.length > 0){
                    ht.setImageUrl(urlArr[0]);
                }
            }

            //室、厅、卫厨、阳台
            String[] layout = getApartments(ald.getApartmentLayout());
            if(layout != null){
                ht.setBedroom(layout.length > 0?layout[0]:null);
                ht.setDrawingRoom(layout.length > 1?layout[1]:null);
                ht.setToilet(layout.length > 2?layout[2]:null);
                ht.setVeranda(layout.length > 3?layout[3]:null);

            }

            houseTypes.add(ht);

        }
        map.put("PremisesImage",list);
        map.put("HouseType",houseTypes);


        return map;
    }
    /**
     * 设置户型
     *
     * @param aprtment
     * @return
     */
    private String[] getApartments(String aprtment) {
        String[] returnStrings = new String[4];
        String[] s = aprtment.split("室");
        if (s.length > 0) {
            returnStrings[0] = "无卧".equals(s[0]) ? "0" : s[0];
            if (s.length == 1) {
                return returnStrings;
            }
        }
        String[] t = s[1].split("厅");
        if (s.length > 0) {
            returnStrings[1] = "无".equals(t[0]) ? "0" : t[0];
            if (t.length == 1) {
                return returnStrings;
            }
        }
        String[] w = t[1].split("卫");
        if (w.length > 0) {
            returnStrings[2] = "无".equals(w[0]) ? "0" : w[0];
            if (w.length == 1) {
                return returnStrings;
            }
        }
        String[] yt = w[1].length() > 3 ? w[1].substring(w[1].length()-3,w[1].length()).split("阳台"): w[1].split("阳台");
        if (yt.length > 0) {
            returnStrings[3] = "无".equals(yt[0]) ? "0" : yt[0];
            return returnStrings;
        }

        return null;
    }

    /**
     * 项目特色 来源于项目标签
     * @return
     */
    private String getFeatureType(String codeName){
        // 查询所有标签
        // 楼盘标签
        if (StringUtils.isNotEmpty(codeName)) {
            String[] labels = codeName.split(",");
            if (labels.length > 0) {
                List<Long> lableList = new ArrayList<Long>();
                for (String b : labels) {
                    lableList.add(Long.parseLong(b));
                }
                Example example = new Example(BaseCodeValue.class);
                example.createCriteria()
                        .andEqualTo("delFlag", DelFlagEnum.UNDEL.getNo())
                        .andIn("id", lableList);
                List<BaseCodeValue> codes = baseCodeValueMapper.selectByExample(example);
                StringBuilder sbCodes = new StringBuilder();
                for (BaseCodeValue bcv : codes) {
                    sbCodes.append(bcv.getCodeName() + ",");
                }
                return sbCodes.substring(0, sbCodes.lastIndexOf(","));
            }
        }

        return null;
    }

    /**
     * 状态转换 V10 审核状态:   1：无效  2：待审   3：未到访      4：已到访
     渠道 审核状态： 0：待审  6：已到访  10：未到访     -1：无效 需要转换
     * @param status
     * @return
     */
    private String switchStatus(String status){
        Map<String,String> statusMap = new HashMap<String,String>(){{
            put("0","2");//待审
            put("6","4");//已到访
            put("10","3");//未到访
            put("-1","1");//无效
        }};
        String returnStatus = statusMap.get(status);
        if(returnStatus == null){
            throw new RuntimeException("未找到对应的状态");
        }
        return returnStatus;
    }

    /**
     * 渠道楼盘销售状态转换V10 楼盘状态
     * @param status
     * @return
     */
    public String switchPremisesStatus(String status){
        Map<String,String> statusMap = new HashMap<String,String>(){
            {
                put("0", "1");//待售
                put("1", "3");//在售
                put("2", "6");//售罄
                // 以下状态未使用
                put("3", "");//在售期房
                put("4", "");//认筹中
                put("5", "");// 尾盘
            }};
        String returnStatus = statusMap.get(status);
        if(StringUtils.isEmpty(returnStatus)){
            return "";
        }
        return returnStatus;
    }

}
